// pages/redux/index.js
// 引入创建store的组件
import createStore from './redux';
// 创建一个默认的state
let defaultState = { count: 0 }
// 创建修改state的纯函数reducer，传入需要修改的状态和要执行的操作
let reducer = (state = defaultState, action) => {
  switch (action.type) {
    case 'ADD':
      return { ...state, count: state.count + action.num };
    case 'MINUS':
      return { ...state, count: state.count - action.num };
    default:
      return state;
  }
}
// 创建全局store
let store = createStore(reducer);
Page({
  data: {},
  onLoad(){
    // 执行订阅，传入修改后执行的监听函数，同时接收当前监听函数的取消订阅方法
    this.unsubscribe = store.subscribe(() => {
      let { count = 0 } = store.getState();
      this.setData({count})
    })
    // 初始化执行页面监听数据
    store.dispatch({type: `@@redux/INIT`});
  },
  add(){
    // 派发ADD的action
    store.dispatch({type: `ADD`, num: 1});
  },
  minus(){
    // 派发MINUS的action
    store.dispatch({type: `MINUS`, num: 1});
  },
  asyncAdd(){
    // 异步派发ADD的action
    setTimeout(() => {
      store.dispatch({type: `ADD`, num: 2});
    }, 2000)
  },
  onUnload() {
    // 页面卸载，取消订阅
    this.unsubscribe();
  }
})